import Vue from "vue";
import VueRouter from "vue-router";
import Store from "@/store";
Vue.use(VueRouter);

const routes = [
  {
    path: "/redirect",
    component: () =>
      import(/* webpackChunkName: "main" */ "@/views/main/index"),
    hidden: true,
    children: [
      {
        path: "/redirect/:path(.*)",
        component: (resolve) => require(["@/views/redirect"], resolve),
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "login" */ "../views/login/index.vue"),
  },
];

const router = new VueRouter({
  routes,
});

// 路由进入前 拦截检查
let routerBeforeCheck = (to, from, next) => {
  let passRouter = ["", "redirect", "error", "home", "login", "demo"];
  if (passRouter.some((e) => to.path.split("/")[1] === e)) {
  } else if (Store.state.auth.routerLoading) {
    setTimeout(() => {
      routerBeforeCheck(to, from, next);
    }, 100);
  } else if (!Store.state.auth.arr.some((e) => e.path === to.path)) {
    return next({
      name: "Error",
      query: {
        errorCode: 404,
      },
    });
  }
  next();
};
router.beforeEach(routerBeforeCheck);

// 获取原型对象push函数
const originalPush = VueRouter.prototype.push;

// 获取原型对象replace函数
const originalReplace = VueRouter.prototype.replace;

// 修改原型对象中的push函数
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

// 修改原型对象中的replace函数
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch((err) => err);
};

export default router;
